package pe.gob.mimp.web.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/download")
public class DownloadController {
	@RequestMapping(value = "/file")
	public ModelAndView handleRequest(
			@RequestParam(value = "file", required = true) String file,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ServletContext servletContext = request.getSession()
				.getServletContext();
		//
		// String file = request.getParameter("file");
		// String fileName = file.substring(file.lastIndexOf("/") + 1);

		File uFile = new File("d:/images/", file);
		int fSize = (int) uFile.length();

		if (fSize > 0) {

			BufferedInputStream in = new BufferedInputStream(
					new FileInputStream(uFile));
			String mimetype = servletContext.getMimeType(file);

			response.setBufferSize(fSize);
			response.setContentType(mimetype);
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ file + "\"");
			response.setContentLength(fSize);

			FileCopyUtils.copy(in, response.getOutputStream());
			in.close();
			response.getOutputStream().flush();
			response.getOutputStream().close();
			// } else {
			// response.setContentType("text/html");
			// PrintWriter printwriter = response.getWriter();
			// printwriter.println("<html>");
			// printwriter.println("<br><br><br><h2>Could not get file name:<br>"
			// + file + "</h2>");
			// printwriter
			// .println("<br><br><br><center><h3><a href='javascript: history.go(-1)'>Back</a></h3></center>");
			// printwriter.println("<br><br><br>&copy; webAccess");
			// printwriter.println("</html>");
			// printwriter.flush();
			// printwriter.close();
		}

		return null;
	}
}
